package com.xiaolei.lib.Activity.bean;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import com.xiaolei.lib.Activity.IActivity;
import android.view.View;
import android.view.View.OnClickListener;

public class ContextClickListener extends LinkedHashMap<View, OnClickHolder> implements OnClickListener
{
	private static final long serialVersionUID = 207469991127511628L;
	
	/**
	 * 为控件注册点击事件
	 * @param view
	 * @param holder
	 */
	public synchronized void registClickListener(View view,OnClickHolder holder)
	{
		this.put(view, holder);
		view.setOnClickListener(this);
	}
	
	/**
	 * 反注册点击事件
	 * @param view
	 */
	public synchronized void unregistClickListener(View view)
	{
		this.remove(view);
	}
	
	@Override
	public void onClick(View view)
	{
		try
		{
			OnClickHolder holder = this.get(view);
			if(holder == null)
				return;
			IActivity activity = holder.activity;
			Method method = holder.method;
			if (!method.isAccessible())
			{
				method.setAccessible(true);
			}
			Class<?>[] params = method.getParameterTypes();
			Object object[] = new Object[params.length];
			try
			{
				for (int i = 0; i < params.length; i++)
				{
					Class<?> class1 = params[i];
					if (class1.isInstance(view))
					{
						object[i] = view;
					}
				}
				method.invoke(activity, object);
			} catch (Exception e)
			{
				try
				{
					method.invoke(activity, new Object[params.length]);
				} catch (Exception e1)
				{
					e1.printStackTrace();
				}
			}
		} catch (Exception e)
		{
		}
	}
}
